package controller;

import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import domain.Article;
import service.IArticleService;

//增   删  改 的controller
@Controller
public class ArticleManagerController {
	@Autowired
	private IArticleService service;

	@RequestMapping("/add")
	public String editView(HttpServletRequest req) {
			//得到 修改 操作的id 转换为Integer 
			String sid = req.getParameter("id"); //直接由参数获取更简单。。。从请求获取获取习惯了。。
			if (sid != null && !"".equals(sid.trim())) {
				Long id = Long.valueOf(sid);
				Article article = service.queryById(id);
				//放到请求里面去把数据查询出来做回显
				req.setAttribute("article", article);
			}
			//不管是编辑还是保存都防止一下（其实对编辑没影响）
			String token = UUID.randomUUID().toString();
			req.setAttribute("tokenInform", token);
			req.getSession().setAttribute("tokenInSession", token);
			return "admin/edit";
	}

	@RequestMapping("/save")
	public String addArt(HttpServletRequest req, String tokenInform) {
		//这里强转不会报空指针 null能转为任意对象类型
		String tokenInSession = (String)req.getSession().getAttribute("tokenInSession");
		if (tokenInform.equals(tokenInSession)) {
			Article art = new Article();
			//得到Article所有属性  其实这里应该当参数传进来。。。。感觉没差别这样好看点
			String keyWord = req.getParameter("keyWord");
			String title = req.getParameter("articleName");
			String content = req.getParameter("content");
			Date writeDate = new Date();

			//将属性设置进去
			art.setArticleName(title);
			art.setKeyWord(keyWord);
			art.setContent(content);
			art.setWriteDate(writeDate);
			//是否成功
			Integer state = null;
			//获取隐藏表单里的数据 判断是编辑还是保存
			String sid = req.getParameter("id");
			if (sid != null && !"".equals(sid.trim())) {
				Long id = Long.valueOf(sid);
				art.setId(id);
				state = service.updateArt(id, art);
			} else {
				state = service.addArt(art);
			}
			if (state > 0) {
				req.setAttribute("isSuccess", "SUCCESS");
			} else {
				req.setAttribute("isSuccess", "FAIL");
			}
			//一次性，用完即销毁 这里不能直接销毁session因为登录信息也在session中
			req.getSession().removeAttribute("tokenInSession");
		}
		return "admin/edit";
	}

	@RequestMapping("/delete")
	public void deleteArt(Long id, HttpServletResponse resp, HttpServletRequest req) throws Exception {
		Integer state = service.deleteArt(id);
		if (state > 0) {
			req.setAttribute("isSuccess", "删除成功");
		} else {
			req.setAttribute("isSuccess", "删除失败");
		}
		//resp.sendRedirect("/BlogSpace/checklogin"); 重定向不能共享数据。。。
		req.getRequestDispatcher("/checklogin").forward(req, resp);
	}
}
